// defined so that we get the stable ABI from 3.2 onwards - means we don't have to 
// recompile this module for every new python version.
#define Py_LIMITED_API
// has to be included first
#include "Python.h"

#include <ApplicationServices/ApplicationServices.h>

static PyObject* sendPaste(PyObject *self, PyObject *args) {
	CGEventRef event = CGEventCreateKeyboardEvent(NULL, /*"v"*/(CGKeyCode)9, /* key down */true);
	CGEventSetFlags(event, kCGEventFlagMaskCommand);
	CGEventPost(kCGHIDEventTap, event);
	CFRelease(event);

	event = CGEventCreateKeyboardEvent(NULL, /*"v"*/(CGKeyCode)9, /* key up */false);
	CGEventSetFlags(event, kCGEventFlagMaskCommand); // command also up again? doesn't seem to matter
	CGEventPost(kCGHIDEventTap, event);
	CFRelease(event);
	
	Py_RETURN_NONE;
}

static PyMethodDef methods[] = { /* see http://docs.python.org/py3k/c-api/structures.html#PyMethodDef */
    {"send_paste",		/* name of python function in module */
	sendPaste,	/* pointer to c function */
	METH_VARARGS,		/* parameters are provided as tuple, if METH_VARARGS | METH_KEYWORDS is
							specified as a third parameter a dictionary of keywords is passed */
	"sends ctrl-v to currently active application" },
    {NULL, NULL, 0, NULL} /* guard */
};

static struct PyModuleDef module = {
    PyModuleDef_HEAD_INIT,	
    "sendpaste",	/* name of module */
    "",		/* doc string */
    -1,		/* size of per-interpreter state of the module,
				or -1 if the module keeps state in global variables. 
				state can be accessed by PyModule_GetState() */
    methods,
    NULL,	/* m_reload: unused, should be null */	
    NULL,	/* m_traverse: A traversal function to call during GC traversal of the module object, 
				or NULL if not needed. */
    NULL,	/* m_clear: A clear function to call during GC clearing of the module object, 
				or NULL if not needed. */
    NULL	/* m_free: A function to call during deallocation of the module object, 
				or NULL if not needed. */
};

PyMODINIT_FUNC PyInit_sendpaste() {
	return PyModule_Create(&module);
}
